from django.shortcuts import render, redirect, HttpResponse


# Create your views here.

# 装饰器
def login_required(fn):
    def inner(request, *args, **kwargs):
        if not request.COOKIES.get('is_login') == '1':
            next = request.path_info
            return redirect('/login/?next={}'.format(next))
        ret = fn(request, *args, **kwargs)
        return ret

    return inner


def login(request):
    if request.method == 'POST':
        username = request.POST.get('user')
        password = request.POST.get('pwd')
        if username == 'leict' and password == 'aaa':
            next = request.GET.get('next')
            if next:
                ret = redirect(next)
            else:
                ret = redirect('/index/')

            ret.set_cookie('is_login', '1', max_age=5)  # max_age 设置超时时间5秒
            return ret

    return render(request, 'login.html')


@login_required
def home(request):
    return HttpResponse("这是Home页面")


@login_required
def index(request):
    return render(request, 'index.html')


# 删除Cookie
def logout(request):
    rep = redirect("/login/")
    rep.delete_cookie("is_login")
    return rep
